<?php
namespace App\Http\Controllers;


use App\Models\User;
use Illuminate\Support\Facades\Auth;
use App\ErrorCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Query\Builder;

class UserController extends Controller
{
    public function __construct(Request $request)
    {
        $this->setParam($request);
    }

    /** 获取api_token (登录之前获取)
     * @return array
     */
    public function getToken( ){
        $userName = $this->getParam('userName');
        $passWord = $this->getParam('passWord');

        if (empty($userName) || empty($passWord)){
            return $this->output(false, ErrorCode::PARAM_NOT_EMPTY);
        }

        $user = User::where('userName', '=', $userName)
            ->where('passWord', '=', md5($passWord))
            ->first();

        $data = [];
        if ($user) {
            $token=str_random(60);
            $user->api_token=$token;
            $user->save();
            $data['api_token'] = $user->api_token;
            return $this->output($data);
        } else {
            return $this->output(false, ErrorCode::USERNAME_NOT_EXISTS);
        }
    }

    /**登陆 login
     * @return array
     */
    public function login(){
        /**©
         * 校验header 的 api_token
         */
        $userInfo = Auth::user();

        if (empty($userInfo)){
            return $this->output(false, ErrorCode::USERNAME_NOT_EXISTS);
        }
        $result['userInfo'] = [
            'userId' => $userInfo['id'],
            'userName' => $userInfo['userName'],
            //'email' => $userInfo['email'],
            'phone' => $userInfo['phone'],
            'roleId' => $userInfo['roleId']
        ];
        return $this->output($result);
    }

    /** 检查用户是否存在
     * @return array
     */
    public function checkUser(){
        $userName = $this->getParam('userName');

        $count = DB::table('user')
            ->where('userName',$userName)
            ->count();
        if($count > 0){
            return $this->output(false,ErrorCode::USER_EXIST);
        }
        return $this->output('success');
    }

    /** 创建用户
     * @return array
     */
    public function create(){
        $userName = $this->getParam('userName');
        $passWord = $this->getParam('passWord');
        //$email = $this->getParam('email');
        $phone = $this->getParam('phone');
        $roleId = $this->getParam('roleId');
        if (empty($userName) || empty($passWord) || empty($phone)){
            return $this->output(false, ErrorCode::PARAM_NOT_EMPTY);
        }
        $bool = DB::table('user')
            ->insert([
                'userName' => $userName,
                'passWord' => md5($passWord),
                //'email' => $email,
                'phone' => $phone,
                'roleId' => $roleId,
                'createTime' => time()
            ]);
        if(!$bool){
            return $this->output(false,ErrorCode::OPERATION_ERROR);
        }
        return $this->output('success');
    }

    /** 获取管理员列表
     * @return array
     */
    public function getUserList(){
        $keyword = $this->getParam('keyword');
        $start = $this->getParam('start');
        $num = $this->getParam('num');
        if(empty($start)&&empty($num)){
            return $this->output(false, ErrorCode::PARAM_ERROR);
        }
        $lists = DB::table('user');
        $lists ->select('id','userName','passWord','phone','roleId','createTime','updateTime');
        if (!empty($keyword)){
            $key = '%' . $keyword . '%';
            $lists->where(function (Builder $query) use($key){
                $query->where('userName','like',$key);
                    ///->orWhere('email','like', $key);
                return $query;
            });
        }
        $lists->orderby('createTime', 'desc');
        if ((int)$num !== -1){
            $list =  $lists->skip($start)->take($num)->get();
        }else{
            $list = $lists->get();
        }

        $res['count'] = count($list);
        $res['items'] = $list;

        return $this->output($res);
    }

    /**获取管理员详情
     * @return array
     */
    public function getUser(){
        $id = $this->getParam('id');
        if(empty($id)){
            return $this->output(false,ErrorCode::PARAM_ERROR);
        }
        $list = DB::table('user')
            ->where('id',$id)
            ->select('id','userName','passWord','phone','roleId','createTime','updateTime')
            ->first();
        $list = json_decode(json_encode($list),1);
        return $this->output($list);
    }

    /** 修改用户信息
     * @return array
     */
    public function updateUser(){
            $id = $this->getParam('id');
            $userName = $this->getParam('userName');
            $passWord = $this->getParam('passWord');
            //$email = $this->getParam('email');
            $phone = $this->getParam('phone');
            $roleId = $this->getParam('roleId');
            if(empty($id) || empty($userName) || empty($phone)){
                return $this->output(false,ErrorCode::PARAM_ERROR);
            }
            if(empty($passWord)){
                $num = DB::table('user')
                    ->where('id',$id)
                    ->update([
                        'userName' => $userName,
                        //'email' => $email,
                        'phone'=>$phone,
                        'roleId' => $roleId,
                        'updateTime' => time(),
                    ]);
                if(!$num){
                    return $this->output(false,ErrorCode::OPERATION_ERROR);
                }
            }else{
                $num = DB::table('user')
                    ->where('id',$id)
                    ->update([
                        'userName' => $userName,
                        'passWord' => md5($passWord),
                       // 'email' => $email,
                        'phone'=>$phone,
                        'roleId' => $roleId,
                        'updateTime' => time(),
                    ]);
                if(!$num){
                    return $this->output(false,ErrorCode::OPERATION_ERROR);
                }
            }

            return $this->output('success');
    }

    /** 删除用户
     * @return array
     */
    public function delUser(){
        $ids = $this->getParam('ids');
        if(empty($ids)){
            return $this->output(false,ErrorCode::PARAM_ERROR);
        }
        foreach ($ids as $id){
            $num = DB::table('user')
                ->where('id',$id)
                ->delete();
            if(!$num){
                return $this->output(false,ErrorCode::OPERATION_ERROR);
            }
        }
        return $this->output('success');
    }

    /**修改密码
     * @return array
     */
    public function updatePwd(){
        $userId = $this->getParam('userId');
        $oldPwd = $this->getParam('oldPwd');
        $newPwd = $this->getParam('newPws');
        if(empty($userId) || empty($oldPwd) || empty($newPwd)){
            return $this->output(false,ErrorCode:: PARAM_ERROR);
        }
        $count = DB::table('user')
            ->where('id',$userId)
            ->where('password',md5($oldPwd))
            ->count();

        if($count <= 0){
            return $this->output(false,ErrorCode::PWD_ERROR);
        }
        $num = DB::table('user')
            ->where('id',$userId)
            ->where('password',md5($oldPwd))
            ->update([
                'password' => md5($newPwd),
                'updateTime' =>time()
            ]);
        if(!$num){
            return $this->output(false,ErrorCode::OPERATION_ERROR);
        }
        return $this->output('success');
    }
}